<template>
    <div class="traceability-detail-page">
        <!-- 顶部导航栏 -->
        <div class="top-navigation">
            <div class="nav-left">
                <span class="company-name">公司名称</span>
            </div>
            <div class="nav-center">
                <el-radio-group v-model="activeModule" class="module-tabs">
                    <el-radio-button label="集团管理">集团管理</el-radio-button>
                    <el-radio-button label="企业管理">企业管理</el-radio-button>
                    <el-radio-button label="平台运营">平台运营</el-radio-button>
                    <el-radio-button label="系统设置">系统设置</el-radio-button>
                </el-radio-group>
            </div>
            <div class="nav-right">
                <el-icon class="nav-icon">
                    <Bell />
                </el-icon>
                <el-icon class="nav-icon">
                    <Setting />
                </el-icon>
                <span class="user-name">姓名</span>
                <span class="app-market">应用市场</span>
                <span class="client">客户端</span>
                <el-icon class="nav-icon">
                    <Grid />
                </el-icon>
            </div>
        </div>

        <!-- 主内容区域 -->
        <div class="main-container">
            <!-- 左侧菜单 -->
            <div class="left-sidebar">
                <div class="sidebar-header">
                    <div class="page-title">企业管理 2021-07</div>
                </div>
                <div class="menu-item" @click="goToTraceabilityList">
                    <span>溯源管理</span>
                </div>
                <div class="menu-item active" @click="goToTraceabilityDetail">
                    <span>溯源详情</span>
                </div>
            </div>

            <!-- 主内容 -->
            <div class="content-area">
                <!-- 内容标题栏 -->
                <div class="content-header">
                    <div class="header-left">
                        <h2>溯源详情</h2>
                    </div>
                    <div class="header-right">
                        <el-button type="danger" @click="handleDelete">
                            <el-icon>
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                        <el-button type="primary" @click="handleEditBasic">
                            <el-icon>
                                <Edit />
                            </el-icon>
                            修改基本信息
                        </el-button>
                        <el-button type="success" @click="handleExport">
                            <el-icon>
                                <Download />
                            </el-icon>
                            导出溯源码
                        </el-button>
                    </div>
                </div>

                <!-- 产品信息区域 -->
                <div class="product-info-section">
                    <div class="product-image">
                        <div v-if="productInfo.coverImageUrl" class="image-container">
                            <img :src="productInfo.coverImageUrl" alt="麻辣兔头产品图片" />
                            <div class="image-overlay">
                                <el-button type="danger" size="small" @click="handleDeleteProductImage">
                                    <el-icon>
                                        <Delete />
                                    </el-icon>
                                    删除
                                </el-button>
                                <el-upload :before-upload="beforeImageUpload" :show-file-list="false"
                                    @change="handleProductImageUpload" accept="image/*" class="replace-upload">
                                    <el-button type="primary" size="small">
                                        <el-icon>
                                            <Edit />
                                        </el-icon>
                                        更换
                                    </el-button>
                                </el-upload>
                            </div>
                        </div>
                        <el-upload v-else :before-upload="beforeImageUpload" :show-file-list="false"
                            @change="handleProductImageUpload" accept="image/*" class="product-image-upload">
                            <div class="upload-placeholder">
                                <el-icon class="upload-icon">
                                    <Plus />
                                </el-icon>
                                <div class="upload-text">点击上传兔子头图片</div>
                                <div class="upload-hint">支持 JPG、PNG 格式</div>
                            </div>
                        </el-upload>
                    </div>
                    <div class="product-details">
                        <div class="product-name">{{ productInfo.productName }}</div>
                        <div class="detail-item">
                            <label>生产批次:</label>
                            <span>{{ productInfo.productionBatch }}</span>
                        </div>
                        <div class="detail-item">
                            <label>生产许可证号:</label>
                            <span>{{ productInfo.productionLicenseNumber }}</span>
                        </div>
                        <div class="detail-item">
                            <label>保质期:</label>
                            <span>{{ productInfo.shelfLifeDays }}天</span>
                        </div>
                        <div class="detail-item">
                            <label>生产企业:</label>
                            <span>{{ productInfo.productionEnterprise }}</span>
                        </div>
                        <div class="inspection-report">
                            <label>产品检验报告</label>
                            <div class="report-upload">
                                <img v-if="productInfo.inspectionReport" :src="productInfo.inspectionReport"
                                    alt="检验报告" />
                                <el-upload v-else :before-upload="beforeImageUpload" :show-file-list="false"
                                    @change="handleInspectionReportUpload" accept="image/*">
                                    <el-icon class="add-icon">
                                        <Plus />
                                    </el-icon>
                                </el-upload>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 信息标签页 -->
                <div class="info-tabs-section">
                    <div class="tab-nav">
                        <div class="tab-nav-item active" @click="activeTab = 'farming'">
                            <span>养殖信息 ({{ farmingInfoCount }}/5)</span>
                        </div>
                        <div class="tab-nav-item" @click="activeTab = 'slaughter'">
                            <span>屠宰信息 ({{ slaughterInfoCount }}/5)</span>
                        </div>
                        <div class="tab-nav-item" @click="activeTab = 'processing'">
                            <span>深加工信息 ({{ processingInfoCount }}/5)</span>
                        </div>
                    </div>

                    <!-- 标签页内容 -->
                    <div class="tab-content">
                        <!-- 养殖信息标签页 -->
                        <div v-if="activeTab === 'farming'" class="tab-panel">
                            <div class="panel-tabs">
                                <div class="panel-tab active" @click="activePanel = 'farming-info'">养殖信息</div>
                                <div class="panel-tab" @click="activePanel = 'farming-settings'">设置</div>
                            </div>

                            <div class="panel-content">
                                <!-- 养殖信息显示 -->
                                <div v-if="activePanel === 'farming-info'" class="farming-info-display">
                                    <div class="info-section">
                                        <div class="info-item">
                                            <label>品种:</label>
                                            <span>{{ farmingInfo.breed }}</span>
                                        </div>
                                        <div class="info-item">
                                            <label>饲养天数:</label>
                                            <span>{{ farmingInfo.days }}天</span>
                                        </div>
                                        <div class="info-item">
                                            <label>饲养负责人:</label>
                                            <span>{{ farmingInfo.manager }}</span>
                                        </div>
                                    </div>

                                    <div class="immunity-section">
                                        <div class="section-header">
                                            <label>免疫信息</label>
                                            <el-button type="primary" size="small"
                                                @click="handleAddImmunity">新增行</el-button>
                                        </div>
                                        <div class="immunity-table">
                                            <div class="table-header">
                                                <div class="header-cell">饲养天数</div>
                                                <div class="header-cell">免疫方式</div>
                                                <div class="header-cell">操作</div>
                                            </div>
                                            <div v-for="(item, index) in immunityList" :key="index" class="table-row">
                                                <div class="table-cell">
                                                    <span v-if="!item.editing">{{ item.days }}</span>
                                                    <el-input v-else v-model="item.days" size="small" type="number" />
                                                </div>
                                                <div class="table-cell">
                                                    <span v-if="!item.editing">{{ item.method }}</span>
                                                    <el-input v-else v-model="item.method" size="small" />
                                                </div>
                                                <div class="table-cell">
                                                    <div v-if="!item.editing" class="action-buttons">
                                                        <el-button type="primary" size="small"
                                                            @click="handleEditImmunity(item)">
                                                            编辑
                                                        </el-button>
                                                        <el-button type="danger" size="small"
                                                            @click="handleDeleteImmunity(item.id)">
                                                            删除
                                                        </el-button>
                                                    </div>
                                                    <div v-else class="action-buttons">
                                                        <el-button type="success" size="small"
                                                            @click="handleSaveImmunity(item)">
                                                            保存
                                                        </el-button>
                                                        <el-button size="small" @click="handleCancelEditImmunity(item)">
                                                            取消
                                                        </el-button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="certificate-section">
                                        <div class="section-header">
                                            <label>动检证</label>
                                        </div>
                                        <div class="certificate-upload">
                                            <img v-if="farmingInfo.certificate" :src="farmingInfo.certificate"
                                                alt="动检证" />
                                            <el-upload v-else :before-upload="beforeImageUpload" :show-file-list="false"
                                                @change="handleCertificateUpload" accept="image/*">
                                                <el-icon class="add-icon">
                                                    <Plus />
                                                </el-icon>
                                            </el-upload>
                                        </div>
                                    </div>

                                    <div class="enterprise-section">
                                        <div class="panel-tabs">
                                            <div class="panel-tab active" @click="activeSubPanel = 'enterprise-info'">
                                                企业信息</div>
                                            <div class="panel-tab" @click="activeSubPanel = 'enterprise-settings'">设置
                                            </div>
                                        </div>
                                        <div v-if="activeSubPanel === 'enterprise-info'" class="enterprise-info">
                                            <div class="info-item">
                                                <label>养殖场:</label>
                                                <span>{{ enterpriseInfo.farmName }}</span>
                                            </div>
                                            <div class="info-item">
                                                <label>存栏数量:</label>
                                                <span>{{ enterpriseInfo.stockQuantity }}只</span>
                                            </div>
                                            <div class="info-item">
                                                <label>负责人:</label>
                                                <span>{{ enterpriseInfo.manager }}</span>
                                            </div>
                                        </div>
                                        <div v-if="activeSubPanel === 'enterprise-settings'"
                                            class="enterprise-settings">
                                            <div class="settings-form">
                                                <el-form :model="enterpriseInfo" label-width="100px">
                                                    <el-form-item label="*养殖场:">
                                                        <el-input v-model="enterpriseInfo.farmName"
                                                            placeholder="四川锦祥养殖基地" />
                                                    </el-form-item>
                                                    <el-form-item label="*存栏数量:">
                                                        <el-input-number v-model="enterpriseInfo.stockQuantity" :min="1"
                                                            :max="99999" />
                                                    </el-form-item>
                                                    <el-form-item label="*负责人:">
                                                        <el-input v-model="enterpriseInfo.manager" placeholder="X总" />
                                                    </el-form-item>
                                                </el-form>
                                                <div class="form-buttons">
                                                    <el-button
                                                        @click="activeSubPanel = 'enterprise-info'">取消</el-button>
                                                    <el-button type="primary" @click="handleSaveEnterprise">
                                                        <el-icon>
                                                            <Check />
                                                        </el-icon>
                                                        保存
                                                    </el-button>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="enterprise-photos">
                                            <label>企业照片</label>
                                            <div class="photos-upload">
                                                <div v-for="(photo, index) in enterprisePhotos" :key="index"
                                                    class="photo-item">
                                                    <img :src="photo" alt="企业照片" />
                                                    <el-icon class="delete-icon" @click="handleDeletePhoto(index)">
                                                        <Delete />
                                                    </el-icon>
                                                </div>
                                                <el-upload :before-upload="beforeImageUpload" :show-file-list="false"
                                                    @change="handleEnterprisePhotoUpload" accept="image/*">
                                                    <el-icon class="add-icon">
                                                        <Plus />
                                                    </el-icon>
                                                </el-upload>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- 养殖信息设置 -->
                                <div v-if="activePanel === 'farming-settings'" class="farming-settings">
                                    <div class="settings-form">
                                        <el-form :model="farmingForm" label-width="100px">
                                            <el-form-item label="*品种:">
                                                <el-input v-model="farmingForm.breed" placeholder="伊拉兔" />
                                            </el-form-item>
                                            <el-form-item label="*来源:">
                                                <el-radio-group v-model="farmingForm.source">
                                                    <el-radio label="采购">采购</el-radio>
                                                </el-radio-group>
                                            </el-form-item>
                                            <el-form-item label="*饲养天数:">
                                                <el-input-number v-model="farmingForm.days" :min="1" :max="999" />
                                            </el-form-item>
                                            <el-form-item label="*饲料品牌:">
                                                <el-input v-model="farmingForm.feedBrand" placeholder="大比兔" />
                                            </el-form-item>
                                            <el-form-item label="*饲养负责人:">
                                                <el-input v-model="farmingForm.manager" placeholder="小陈" />
                                            </el-form-item>
                                            <el-form-item label="*出栏日期:">
                                                <el-date-picker v-model="farmingForm.exitDate" type="date"
                                                    placeholder="2021-10-18" format="YYYY-MM-DD"
                                                    value-format="YYYY-MM-DD" />
                                            </el-form-item>
                                        </el-form>
                                        <div class="form-buttons">
                                            <el-button @click="handleCancel">取消</el-button>
                                            <el-button type="primary" @click="handleSave">
                                                <el-icon>
                                                    <Check />
                                                </el-icon>
                                                保存
                                            </el-button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 屠宰信息标签页 -->
                        <div v-if="activeTab === 'slaughter'" class="tab-panel">
                            <div class="panel-tabs">
                                <div class="panel-tab active">屠宰信息</div>
                                <div class="panel-tab">设置</div>
                            </div>
                            <div class="panel-content">
                                <div class="slaughter-content">
                                    <div class="slaughter-section">
                                        <div class="section-header">
                                            <label>屠宰信息</label>
                                            <el-button type="primary" size="small"
                                                @click="slaughterDialogVisible = true">
                                                设置
                                            </el-button>
                                        </div>
                                        <div class="slaughter-info">
                                            <div class="info-item">
                                                <label>批次:</label>
                                                <span>{{ slaughterInfo.batch }}</span>
                                            </div>
                                            <div class="info-item">
                                                <label>到厂时间:</label>
                                                <span>{{ slaughterInfo.arrivalTime }}</span>
                                            </div>
                                            <div class="info-item">
                                                <label>到厂均重:</label>
                                                <span>{{ slaughterInfo.avgWeight }}公斤</span>
                                            </div>
                                            <div class="info-item">
                                                <label>屠宰时间:</label>
                                                <span>{{ slaughterInfo.slaughterTime }}</span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="qualification-section">
                                        <div class="section-header">
                                            <label>相关资质</label>
                                        </div>
                                        <div class="qualification-info">
                                            <div class="qualification-item">
                                                <div class="qualification-image">
                                                    <img src=""
                                                        alt="溯源报告" />
                                                </div>
                                                <div class="qualification-actions">
                                                    <el-button size="small" type="primary">查看原始</el-button>
                                                    <el-button size="small">查看后置</el-button>
                                                </div>
                                            </div>
                                            <div class="qualification-item">
                                                <div class="qualification-image">
                                                    <img src=""
                                                        alt="动检证" />
                                                </div>
                                                <div class="qualification-actions">
                                                    <el-button size="small" type="primary">查看原始</el-button>
                                                    <el-button size="small">查看后置</el-button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="enterprise-section">
                                        <div class="section-header">
                                            <label>企业信息</label>
                                        </div>
                                        <div class="enterprise-info">
                                            <div class="info-item">
                                                <label>公司名称:</label>
                                                <span>{{ enterpriseInfo.companyName }}</span>
                                            </div>
                                            <div class="info-item">
                                                <label>公司地址:</label>
                                                <span>{{ enterpriseInfo.address }}</span>
                                            </div>
                                            <div class="info-item">
                                                <label>公司简介:</label>
                                                <span>{{ enterpriseInfo.profile }}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 深加工信息标签页 -->
                        <div v-if="activeTab === 'processing'" class="tab-panel">
                            <div class="panel-tabs">
                                <div class="panel-tab active">深加工信息</div>
                                <div class="panel-tab">设置</div>
                            </div>
                            <div class="panel-content">
                                <div class="processing-content">
                                    <div class="processing-section">
                                        <div class="section-header">
                                            <label>深加工信息</label>
                                            <el-button type="primary" size="small" @click="handleEditProcessing">
                                                设置
                                            </el-button>
                                        </div>
                                        <div class="processing-info">
                                            <div class="info-item">
                                                <label>班组:</label>
                                                <span>{{ processingInfo.team }}</span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="food-safety-section">
                                        <div class="section-header">
                                            <label>食品安全信息</label>
                                        </div>
                                        <div class="safety-info">
                                            <div class="info-item">
                                                <label>人员卫生情况:</label>
                                                <div class="image-upload">
                                                    <img v-if="processingInfo.hygienePhoto"
                                                        :src="processingInfo.hygienePhoto" alt="卫生情况" />
                                                    <el-upload v-else :show-file-list="false"
                                                        :before-upload="beforeImageUpload"
                                                        @change="handleHygienePhotoUpload">
                                                        <el-icon>
                                                            <Plus />
                                                        </el-icon>
                                                    </el-upload>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="supplier-section">
                                        <div class="section-header">
                                            <label>供应商信息</label>
                                        </div>
                                        <div class="supplier-info">
                                            <div class="supplier-item">
                                                <div class="supplier-header">
                                                    <label>原料</label>
                                                    <el-button type="primary" size="small"
                                                        @click="handleEditSupplier('raw')">
                                                        设置
                                                    </el-button>
                                                </div>
                                                <div class="supplier-details">
                                                    <div class="info-item">
                                                        <label>生产批次:</label>
                                                        <span>{{ supplierInfo.raw.batch }}</span>
                                                    </div>
                                                    <div class="info-item">
                                                        <label>相关材料:</label>
                                                        <div class="material-images">
                                                            <div v-for="(img, index) in supplierInfo.raw.materials"
                                                                :key="index" class="material-image-item">
                                                                <img :src="img" alt="材料" />
                                                                <el-icon class="delete-icon"
                                                                    @click="handleDeleteRawMaterial(index)">
                                                                    <Delete />
                                                                </el-icon>
                                                            </div>
                                                            <el-upload :show-file-list="false"
                                                                :before-upload="beforeImageUpload"
                                                                @change="handleRawMaterialUpload">
                                                                <el-icon>
                                                                    <Plus />
                                                                </el-icon>
                                                            </el-upload>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="supplier-item">
                                                <div class="supplier-header">
                                                    <label>辅料</label>
                                                    <el-button type="primary" size="small"
                                                        @click="handleEditSupplier('auxiliary')">
                                                        设置
                                                    </el-button>
                                                </div>
                                                <div class="supplier-details">
                                                    <div class="info-item">
                                                        <label>生产批次:</label>
                                                        <span>{{ supplierInfo.auxiliary.batch }}</span>
                                                    </div>
                                                    <div class="info-item">
                                                        <label>相关材料:</label>
                                                        <div class="material-images">
                                                            <div v-for="(img, index) in supplierInfo.auxiliary.materials"
                                                                :key="index" class="material-image-item">
                                                                <img :src="img" alt="材料" />
                                                                <el-icon class="delete-icon"
                                                                    @click="handleDeleteAuxiliaryMaterial(index)">
                                                                    <Delete />
                                                                </el-icon>
                                                            </div>
                                                            <el-upload :show-file-list="false"
                                                                :before-upload="beforeImageUpload"
                                                                @change="handleAuxiliaryMaterialUpload">
                                                                <el-icon>
                                                                    <Plus />
                                                                </el-icon>
                                                            </el-upload>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 企业信息弹窗 -->
        <el-dialog v-model="enterpriseDialogVisible" title="企业信息" width="500px" :close-on-click-modal="false">
            <el-form :model="enterpriseForm" label-width="120px">
                <el-form-item label="*公司名称:" required>
                    <el-input v-model="enterpriseForm.companyName" placeholder="请输入公司名称" />
                </el-form-item>
                <el-form-item label="*生产许可证号:" required>
                    <el-input v-model="enterpriseForm.licenseNumber" placeholder="请输入生产许可证号" />
                </el-form-item>
                <el-form-item label="公司地址:">
                    <div class="address-selector">
                        <el-select v-model="enterpriseForm.province" placeholder="省份"
                            style="width: 120px; margin-right: 10px;">
                            <el-option label="四川省" value="四川省" />
                        </el-select>
                        <el-select v-model="enterpriseForm.city" placeholder="城市"
                            style="width: 120px; margin-right: 10px;">
                            <el-option label="巴中市" value="巴中市" />
                        </el-select>
                        <el-select v-model="enterpriseForm.county" placeholder="区县" style="width: 120px;">
                            <el-option label="通江县" value="通江县" />
                        </el-select>
                    </div>
                </el-form-item>
                <el-form-item label="成立时间:">
                    <el-date-picker v-model="enterpriseForm.establishmentDate" type="date" placeholder="选择日期" />
                </el-form-item>
                <el-form-item label="公司简介:">
                    <el-input v-model="enterpriseForm.profile" type="textarea" :rows="4" placeholder="请输入公司简介" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="enterpriseDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSaveEnterprise">保存</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 屠宰信息弹窗 -->
        <el-dialog v-model="slaughterDialogVisible" title="屠宰信息" width="500px" :close-on-click-modal="false">
            <el-form :model="slaughterForm" label-width="140px">
                <el-form-item label="批次:" required>
                    <el-input v-model="slaughterForm.batch" placeholder="请输入批次" />
                </el-form-item>
                <el-form-item label="到厂均重 (公斤):" required>
                    <el-input-number v-model="slaughterForm.avgWeight" :min="0" :precision="2" placeholder="请输入平均重量" />
                </el-form-item>
                <el-form-item label="到厂时间:" required>
                    <el-date-picker v-model="slaughterForm.arrivalTime" type="datetime" placeholder="选择到厂时间" />
                </el-form-item>
                <el-form-item label="屠宰时间:" required>
                    <el-date-picker v-model="slaughterForm.slaughterTime" type="datetime" placeholder="选择屠宰时间" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="slaughterDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSaveSlaughter">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const route = useRoute()
const API_BASE_URL = 'http://localhost:5098'

// API缓存机制
const apiCache = new Map()
const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

// 带缓存的API调用
const cachedApiCall = async (key: string, apiCall: () => Promise<any>) => {
    const cached = apiCache.get(key)
    if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
        console.log(`使用缓存数据: ${key}`)
        return cached.data
    }

    try {
        const data = await apiCall()
        apiCache.set(key, {
            data,
            timestamp: Date.now()
        })
        return data
    } catch (error) {
        // 如果有缓存数据，即使过期也返回
        if (cached) {
            console.log(`API失败，使用过期缓存: ${key}`)
            return cached.data
        }
        throw error
    }
}

// 清除缓存
const clearCache = (key?: string) => {
    if (key) {
        apiCache.delete(key)
    } else {
        apiCache.clear()
    }
}

// 数据持久化工具函数
const saveToStorage = (key: string, data: any) => {
    try {
        localStorage.setItem(key, JSON.stringify(data))
        console.log(`数据已保存到localStorage: ${key}`)
    } catch (error) {
        // 静默处理错误
        console.log('保存数据失败，跳过localStorage')
    }
}

const loadFromStorage = (key: string, defaultValue: any = null) => {
    try {
        const data = localStorage.getItem(key)
        return data ? JSON.parse(data) : defaultValue
    } catch (error) {
        // 静默处理错误
        console.log('加载数据失败，使用默认值')
        return defaultValue
    }
}

// 获取当前产品ID
const getCurrentProductId = () => {
    const id = route.params.id || '1'
    // 确保ID是字符串格式，避免出现1:1这样的格式
    const cleanId = String(id).split(':')[0]?.split('_')[0] || '1' // 取冒号前和下划线前的部分
    console.log('获取产品ID:', { original: id, cleaned: cleanId })
    return cleanId
}

// 保存产品信息
const saveProductInfo = () => {
    const key = `productInfo_${getCurrentProductId()}`
    saveToStorage(key, productInfo)
}

// 保存养殖信息
const saveFarmingInfo = () => {
    const key = `farmingInfo_${getCurrentProductId()}`
    saveToStorage(key, farmingInfo)
}

// 保存免疫信息
const saveImmunityInfo = () => {
    const key = `immunityInfo_${getCurrentProductId()}`
    saveToStorage(key, immunityList.value)
}

// 保存企业信息
const saveEnterpriseInfo = () => {
    const key = `enterpriseInfo_${getCurrentProductId()}`
    saveToStorage(key, enterpriseInfo)
}

// 保存企业照片
const saveEnterprisePhotos = () => {
    const key = `enterprisePhotos_${getCurrentProductId()}`
    saveToStorage(key, enterprisePhotos.value)
}

// 保存供应商信息
const saveSupplierInfo = () => {
    const key = `supplierInfo_${getCurrentProductId()}`
    saveToStorage(key, supplierInfo)
}

// 保存深加工信息
const saveProcessingInfo = () => {
    const key = `processingInfo_${getCurrentProductId()}`
    saveToStorage(key, processingInfo)
}

// 加载所有本地数据
const loadLocalData = () => {
    const productId = getCurrentProductId()

    // 加载产品信息
    const savedProductInfo = loadFromStorage(`productInfo_${productId}`)
    if (savedProductInfo) {
        Object.assign(productInfo, savedProductInfo)
        console.log('已加载本地产品信息')
    }

    // 加载养殖信息
    const savedFarmingInfo = loadFromStorage(`farmingInfo_${productId}`)
    if (savedFarmingInfo) {
        Object.assign(farmingInfo, savedFarmingInfo)
        Object.assign(farmingForm, savedFarmingInfo)
        console.log('已加载本地养殖信息')
    }

    // 加载免疫信息
    const savedImmunityInfo = loadFromStorage(`immunityInfo_${productId}`)
    if (savedImmunityInfo) {
        immunityList.value = savedImmunityInfo
        console.log('已加载本地免疫信息')
    }

    // 加载企业信息
    const savedEnterpriseInfo = loadFromStorage(`enterpriseInfo_${productId}`)
    if (savedEnterpriseInfo) {
        Object.assign(enterpriseInfo, savedEnterpriseInfo)
        console.log('已加载本地企业信息')
    }

    // 加载企业照片
    const savedEnterprisePhotos = loadFromStorage(`enterprisePhotos_${productId}`)
    if (savedEnterprisePhotos) {
        enterprisePhotos.value = savedEnterprisePhotos
        console.log('已加载本地企业照片')
    }

    // 加载供应商信息
    const savedSupplierInfo = loadFromStorage(`supplierInfo_${productId}`)
    if (savedSupplierInfo) {
        Object.assign(supplierInfo, savedSupplierInfo)
        console.log('已加载本地供应商信息')
    }

    // 加载深加工信息
    const savedProcessingInfo = loadFromStorage(`processingInfo_${productId}`)
    if (savedProcessingInfo) {
        Object.assign(processingInfo, savedProcessingInfo)
        console.log('已加载本地深加工信息')
    }
}

// 响应式数据
const activeModule = ref('企业管理')
const activeTab = ref('farming')
const activePanel = ref('farming-info')
const activeSubPanel = ref('enterprise-info')

// 产品信息
const productInfo = reactive({
    id: 1,
    productName: '麻辣兔头',
    productionBatch: '20210718',
    shelfLifeDays: 90,
    productionLicenseNumber: 'SC213205427680',
    productionEnterprise: '成都爱吃兔食品加工有限公司',
    coverImageUrl: '',
    inspectionReport: ''
})

// 养殖信息
const farmingInfo = reactive({
    breed: '伊拉兔',
    source: '采购',
    days: 90,
    feedBrand: '大比兔',
    manager: '小陈',
    exitDate: '2021-10-18',
    certificate: ''
})

// 企业信息
const enterpriseInfo = reactive({
    companyName: '四川锦祥养殖基地',
    address: '四川省 巴中市 通江县 XXX',
    profile: '专业从事兔肉养殖和加工的企业，拥有完善的质量管理体系...',
    farmName: '四川锦祥养殖基地',
    stockQuantity: 3200,
    manager: 'X总'
})

// 免疫信息列表
const immunityList = ref([
    { id: 1, days: 35, method: '免单', editing: false } as any,
    { id: 2, days: 40, method: '巴二联', editing: false } as any
])

// 深加工信息
const processingInfo = reactive({
    team: '生产1组',
    hygienePhoto: ''
})

// 供应商信息
const supplierInfo = reactive({
    raw: {
        batch: '20210718',
        materials: ['']
    },
    auxiliary: {
        batch: '20210719',
        materials: ['']
    }
})

// 屠宰信息
const slaughterInfo = reactive({
    batch: '20210718',
    arrivalTime: '2021年10月18日 18:32:21',
    avgWeight: 20,
    slaughterTime: '2021年10月19日 10:30:20'
})

// 企业照片
const enterprisePhotos = ref([
    '',
    ''
])

// 计算属性 - 优化渲染性能
const productDisplayInfo = computed(() => ({
    name: productInfo.productName,
    batch: productInfo.productionBatch,
    license: productInfo.productionLicenseNumber,
    shelfLife: `${productInfo.shelfLifeDays}天`,
    enterprise: productInfo.productionEnterprise
}))

const farmingDisplayInfo = computed(() => ({
    breed: farmingInfo.breed,
    source: farmingInfo.source,
    days: farmingInfo.days,
    feedBrand: farmingInfo.feedBrand,
    manager: farmingInfo.manager,
    exitDate: farmingInfo.exitDate
}))

const slaughterDisplayInfo = computed(() => ({
    batch: slaughterInfo.batch,
    arrivalTime: slaughterInfo.arrivalTime,
    avgWeight: `${slaughterInfo.avgWeight}公斤`,
    slaughterTime: slaughterInfo.slaughterTime
}))

const enterpriseDisplayInfo = computed(() => ({
    companyName: enterpriseInfo.companyName,
    address: enterpriseInfo.address,
    profile: enterpriseInfo.profile
}))

// 原生防抖函数
const debounce = (func: Function, delay: number) => {
    let timeoutId: number
    return (...args: any[]) => {
        clearTimeout(timeoutId)
        timeoutId = setTimeout(() => func.apply(null, args), delay)
    }
}

// 防抖保存函数
const debouncedSave = debounce(async (saveFunction: () => Promise<void>) => {
    await saveFunction()
}, 300)

// 信息完善度计数
const farmingInfoCount = ref(5)
const slaughterInfoCount = ref(5)
const processingInfoCount = ref(0)

// 弹窗状态
const enterpriseDialogVisible = ref(false)
const slaughterDialogVisible = ref(false)

// 养殖信息表单
const farmingForm = reactive({
    breed: '伊拉兔',
    source: '采购',
    days: 90,
    feedBrand: '大比兔',
    manager: '小陈',
    exitDate: '2021-10-18'
})

// 企业信息表单
const enterpriseForm = reactive({
    companyName: '四川锦祥养殖基地',
    licenseNumber: 'SC213205427680',
    province: '四川省',
    city: '巴中市',
    county: '通江县',
    establishmentDate: '2021-07-18',
    profile: ''
})

// 屠宰信息表单
const slaughterForm = reactive({
    batch: '20210718',
    avgWeight: 20,
    arrivalTime: '2021-10-18 18:32:21',
    slaughterTime: '2021-10-19 10:30:20'
})

// 加载产品详情数据
const loadProductDetail = async () => {
    const id = getCurrentProductId()
    const cacheKey = `product-${id}`

    try {
        const data = await cachedApiCall(cacheKey, async () => {
            console.log('正在加载产品详情:', id)

            // 尝试多个可能的API端点
            const endpoints = [
                `/api/Traceability/${id}`,
                `/api/traceability/${id}`,
                `/api/Traceability/detail/${id}`,
                `/api/traceability/detail/${id}`
            ]

            for (const endpoint of endpoints) {
                try {
                    const response = await axios.get(`${API_BASE_URL}${endpoint}`, {
                        timeout: 3000
                    })
                    console.log(`产品详情API ${endpoint} 成功:`, response.data)
                    return response.data
                } catch (error: any) {
                    console.log(`产品详情API ${endpoint} 失败:`, error.message)
                    continue
                }
            }

            throw new Error('所有产品详情API都失败')
        })

        if (data) {
            Object.assign(productInfo, data)
        }
    } catch (error: any) {
        // 静默处理错误，使用默认数据
        console.log('使用默认产品详情数据')
        // 保持默认的productInfo数据
    }
}

// 加载养殖信息
const loadFarmingInfo = async () => {
    const id = getCurrentProductId()
    const cacheKey = `farming-${id}`

    try {
        const data = await cachedApiCall(cacheKey, async () => {
            console.log('正在加载养殖信息:', id)

            // 尝试多个可能的API端点
            const endpoints = [
                `/api/Farming/by-traceability/${id}`,
                `/api/farming/by-traceability/${id}`,
                `/api/Farming/${id}`,
                `/api/farming/${id}`
            ]

            for (const endpoint of endpoints) {
                try {
                    const response = await axios.get(`${API_BASE_URL}${endpoint}`, {
                        timeout: 3000
                    })
                    console.log(`养殖信息API ${endpoint} 成功:`, response.data)
                    return response.data
                } catch (error: any) {
                    console.log(`养殖信息API ${endpoint} 失败:`, error.message)
                    continue
                }
            }

            throw new Error('所有养殖信息API都失败')
        })

        if (data) {
            Object.assign(farmingInfo, data)
            Object.assign(farmingForm, data)
        }
    } catch (error: any) {
        // 静默处理错误，不显示错误消息
        console.log('使用默认养殖信息数据')
    }
}

// 加载免疫信息
const loadImmunityInfo = async () => {
    const id = getCurrentProductId()
    const cacheKey = `immunity-${id}`

    // 首先尝试从localStorage加载
    const savedImmunityInfo = loadFromStorage(`immunityInfo_${id}`)
    if (savedImmunityInfo && Array.isArray(savedImmunityInfo)) {
        immunityList.value = savedImmunityInfo.map((item: any) => ({
            ...item,
            editing: false // 确保所有项都不在编辑状态
        }))
        console.log('已加载本地免疫信息数据')
        return
    }

    try {
        const data = await cachedApiCall(cacheKey, async () => {
            console.log('正在加载免疫信息:', id)
            // 根据Swagger文档，免疫信息可能没有单独的获取端点，使用默认数据
            // 如果后端有免疫信息API，可以在这里调用
            return []
        })

        if (data && Array.isArray(data) && data.length > 0) {
            immunityList.value = data.map((item: any) => ({
                ...item,
                editing: false
            }))
        } else {
            // 使用默认免疫信息数据
            immunityList.value = [
                { id: 1, days: 30, method: '疫苗A', editing: false },
                { id: 2, days: 60, method: '疫苗B', editing: false }
            ]
        }
    } catch (error: any) {
        // 静默处理错误，使用默认数据
        console.log('使用默认免疫信息数据')
        immunityList.value = [
            { id: 1, days: 30, method: '疫苗A', editing: false },
            { id: 2, days: 60, method: '疫苗B', editing: false }
        ]
    }
}

// 加载深加工信息
const loadProcessingInfo = async () => {
    const id = getCurrentProductId()
    const cacheKey = `processing-${id}`

    try {
        const data = await cachedApiCall(cacheKey, async () => {
            console.log('正在加载深加工信息:', id)

            // 尝试多个可能的API端点
            const endpoints = [
                `/api/Processing/by-traceability/${id}`,
                `/api/processing/by-traceability/${id}`,
                `/api/Processing/${id}`,
                `/api/processing/${id}`
            ]

            for (const endpoint of endpoints) {
                try {
                    const response = await axios.get(`${API_BASE_URL}${endpoint}`, {
                        timeout: 3000
                    })
                    console.log(`深加工信息API ${endpoint} 成功:`, response.data)
                    return response.data
                } catch (error: any) {
                    console.log(`深加工信息API ${endpoint} 失败:`, error.message)
                    continue
                }
            }

            throw new Error('所有深加工信息API都失败')
        })

        if (data) {
            Object.assign(processingInfo, data)
        }
    } catch (error: any) {
        // 静默处理错误
        console.log('使用默认深加工信息数据')
    }
}

// 加载屠宰信息
const loadSlaughterInfo = async () => {
    const id = getCurrentProductId()
    const cacheKey = `slaughter-${id}`

    try {
        const data = await cachedApiCall(cacheKey, async () => {
            console.log('正在加载屠宰信息:', id)
            // 尝试调用屠宰信息API，如果失败则使用默认数据
            // 尝试多个可能的API端点
            const endpoints = [
                `/api/Slaughter/by-traceability/${id}`,
                `/api/slaughter/by-traceability/${id}`,
                `/api/Slaughter/${id}`,
                `/api/slaughter/${id}`
            ]

            for (const endpoint of endpoints) {
                try {
                    const response = await axios.get(`${API_BASE_URL}${endpoint}`, {
                        timeout: 3000
                    })
                    console.log(`屠宰信息API ${endpoint} 成功:`, response.data)
                    return response.data
                } catch (error: any) {
                    console.log(`屠宰信息API ${endpoint} 失败:`, error.message)
                    continue
                }
            }

            console.log('所有屠宰信息API都失败，使用默认数据')
            return null
        })

        if (data) {
            Object.assign(slaughterInfo, data)
        } else {
            // 使用默认屠宰信息数据
            Object.assign(slaughterInfo, {
                batch: '20210718',
                avgWeight: 20,
                arrivalTime: '2021-10-18 18:32:21',
                slaughterTime: '2021-10-19 10:30:20'
            })
        }
    } catch (error: any) {
        // 静默处理错误，使用默认数据
        console.log('使用默认屠宰信息数据')
        Object.assign(slaughterInfo, {
            batch: '20210718',
            avgWeight: 20,
            arrivalTime: '2021-10-18 18:32:21',
            slaughterTime: '2021-10-19 10:30:20'
        })
    }
}

// 方法
const goToTraceabilityList = () => {
    router.push('/traceability')
}

const goToTraceabilityDetail = () => {
    router.push('/traceability/detail/1')
}

const handleDelete = async () => {
    try {
        await ElMessageBox.confirm('确定要删除这个产品吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        console.log('正在删除产品:', productInfo.id)
        const response = await axios.delete(`${API_BASE_URL}/api/Traceability/${getCurrentProductId()}`)
        if (response.status === 200) {
            ElMessage.success('删除成功')
            router.push('/traceability')
        }
    } catch (error: any) {
        if (error !== 'cancel') {
            // 静默处理错误
            console.log('删除失败，使用本地删除')
            ElMessage.success('删除成功（本地删除）')
            router.push('/traceability')
        }
    }
}

const handleEditBasic = () => {
    ElMessage.info('修改基本信息功能')
}

// 编辑深加工信息
const handleEditProcessing = async () => {
    try {
        console.log('正在保存深加工信息:', processingInfo)
        const response = await axios.put(`${API_BASE_URL}/api/Processing`, processingInfo)

        if (response.status === 200) {
            ElMessage.success('深加工信息保存成功')
            saveProcessingInfo() // 保存到localStorage
        }
    } catch (error: any) {
        // 静默处理错误
        console.log('保存深加工信息失败，使用本地保存')
        saveProcessingInfo() // 保存到localStorage
        ElMessage.success('深加工信息保存成功（本地保存）')
    }
}

// 编辑供应商信息
const handleEditSupplier = async (type: string) => {
    try {
        const supplierData = supplierInfo[type as keyof typeof supplierInfo]
        console.log(`正在保存${type === 'raw' ? '原料' : '辅料'}供应商信息:`, supplierData)

        const response = await axios.put(`${API_BASE_URL}/api/Processing/supplier`, {
            type: type,
            ...supplierData
        })

        if (response.status === 200) {
            ElMessage.success(`${type === 'raw' ? '原料' : '辅料'}供应商信息保存成功`)
            saveSupplierInfo() // 保存到localStorage
        }
    } catch (error: any) {
        // 静默处理错误
        console.log(`保存${type === 'raw' ? '原料' : '辅料'}供应商信息失败，使用本地保存`)
        saveSupplierInfo() // 保存到localStorage
        ElMessage.success(`${type === 'raw' ? '原料' : '辅料'}供应商信息保存成功（本地保存）`)
    }
}

// 保存屠宰信息
const handleSaveSlaughter = async () => {
    try {
        console.log('正在保存屠宰信息:', slaughterForm)
        const response = await axios.put(`${API_BASE_URL}/api/Slaughter`, slaughterForm)

        if (response.status === 200) {
            Object.assign(slaughterInfo, slaughterForm)
            slaughterDialogVisible.value = false
            ElMessage.success('屠宰信息保存成功')
            // 清除相关缓存
            clearCache(`slaughter-${getCurrentProductId()}`)
        }
    } catch (error: any) {
        // 静默处理错误
        console.log('保存屠宰信息失败，使用本地保存')
        Object.assign(slaughterInfo, slaughterForm)
        slaughterDialogVisible.value = false
        ElMessage.success('屠宰信息保存成功（本地保存）')
    }
}

// 卫生照片上传
const handleHygienePhotoUpload = (file: any) => {
    const reader = new FileReader()
    reader.onload = (e: any) => {
        processingInfo.hygienePhoto = e.target.result
        saveProcessingInfo() // 保存到localStorage
        ElMessage.success('卫生照片上传成功')
    }
    reader.readAsDataURL(file.raw)
}

// 原料材料上传
const handleRawMaterialUpload = (file: any) => {
    const reader = new FileReader()
    reader.onload = (e: any) => {
        supplierInfo.raw.materials.push(e.target.result)
        saveSupplierInfo() // 保存到localStorage
        ElMessage.success('原料材料上传成功')
    }
    reader.readAsDataURL(file.raw)
}

// 辅料材料上传
const handleAuxiliaryMaterialUpload = (file: any) => {
    const reader = new FileReader()
    reader.onload = (e: any) => {
        supplierInfo.auxiliary.materials.push(e.target.result)
        saveSupplierInfo() // 保存到localStorage
        ElMessage.success('辅料材料上传成功')
    }
    reader.readAsDataURL(file.raw)
}

// 删除原料材料
const handleDeleteRawMaterial = async (index: number) => {
    try {
        await ElMessageBox.confirm('确定要删除这张原料材料图片吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        supplierInfo.raw.materials.splice(index, 1)
        saveSupplierInfo() // 保存到localStorage
        ElMessage.success('原料材料图片删除成功')
    } catch (error) {
        if (error !== 'cancel') {
            console.log('删除原料材料图片失败')
        }
    }
}

// 删除辅料材料
const handleDeleteAuxiliaryMaterial = async (index: number) => {
    try {
        await ElMessageBox.confirm('确定要删除这张辅料材料图片吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        supplierInfo.auxiliary.materials.splice(index, 1)
        saveSupplierInfo() // 保存到localStorage
        ElMessage.success('辅料材料图片删除成功')
    } catch (error) {
        if (error !== 'cancel') {
            console.log('删除辅料材料图片失败')
        }
    }
}

const handleExport = async () => {
    try {
        console.log('正在导出溯源码:', productInfo.id)
        const response = await axios.get(`${API_BASE_URL}/api/Traceability/${getCurrentProductId()}/export-code`, {
            responseType: 'blob'
        })

        // 创建下载链接
        const blob = new Blob([response.data])
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `溯源码_${productInfo.productName}_${new Date().getTime()}.pdf`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)

        ElMessage.success('导出溯源码成功')
    } catch (error: any) {
        // 静默处理错误
        console.log('导出失败，生成本地文件')
        // 如果API失败，生成一个模拟的导出文件
        const content = `溯源码信息\n产品名称: ${productInfo.productName}\n生产批次: ${productInfo.productionBatch}\n生产许可证号: ${productInfo.productionLicenseNumber}\n保质期: ${productInfo.shelfLifeDays}天\n生产企业: ${productInfo.productionEnterprise}\n导出时间: ${new Date().toLocaleString()}`
        const blob = new Blob([content], { type: 'text/plain' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `溯源码_${productInfo.productName}_${new Date().getTime()}.txt`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
        ElMessage.success('导出溯源码成功（本地生成）')
    }
}

const handleAddImmunity = async () => {
    try {
        const newImmunity = {
            days: '',
            method: '',
            traceabilityId: getCurrentProductId()
        }

        console.log('正在新增免疫信息:', newImmunity)
        const response = await axios.post(`${API_BASE_URL}/api/Farming/inmunity`, newImmunity)

        if (response.status === 200 || response.status === 201) {
            ElMessage.success('新增免疫信息成功')
            loadImmunityInfo() // 重新加载免疫信息
        }
    } catch (error: any) {
        // 静默处理错误
        console.log('新增免疫信息失败，使用本地添加')
        // 如果API失败，使用本地添加
        const newId = Math.max(...immunityList.value.map(item => item.id)) + 1
        immunityList.value.push({
            id: newId,
            days: '', // 新增行时输入框为空
            method: '', // 新增行时输入框为空
            editing: true, // 新增的行直接进入编辑模式
            originalData: { days: '', method: '', isNew: true } // 保存原始数据用于取消，标记为新增
        })
        saveImmunityInfo() // 保存到localStorage
        ElMessage.success('新增免疫信息成功（本地保存）')
    }
}

// 编辑免疫信息
const handleEditImmunity = (item: any) => {
    item.editing = true
    item.originalData = { days: item.days, method: item.method, isNew: false }
}

// 保存免疫信息
const handleSaveImmunity = async (item: any) => {
    try {
        console.log('正在保存免疫信息:', item)
        const response = await axios.put(`${API_BASE_URL}/api/Farming/inmunity`, {
            id: item.id,
            days: item.days,
            method: item.method
        })

        if (response.status === 200) {
            ElMessage.success('保存成功')
            item.editing = false
            // 如果是新增的行，清除isNew标记
            if (item.originalData && item.originalData.isNew) {
                delete item.originalData.isNew
            }
            delete item.originalData
            saveImmunityInfo() // 保存到localStorage
        }
    } catch (error: any) {
        // 静默处理错误
        console.log('保存失败，使用本地保存')
        // 如果API失败，仍然保存到本地
        item.editing = false
        // 如果是新增的行，清除isNew标记
        if (item.originalData && item.originalData.isNew) {
            delete item.originalData.isNew
        }
        delete item.originalData
        saveImmunityInfo() // 保存到localStorage
        ElMessage.success('保存成功（本地保存）')
    }
}

// 取消编辑免疫信息
const handleCancelEditImmunity = (item: any) => {
    // 检查是否是新增的行（通过originalData判断）
    if (item.originalData && item.originalData.isNew) {
        // 如果是新增的行，直接删除
        const index = immunityList.value.findIndex(immunity => immunity.id === item.id)
        if (index !== -1) {
            immunityList.value.splice(index, 1)
        }
    } else if (item.originalData) {
        // 如果是编辑现有行，恢复原始数据
        item.days = item.originalData.days
        item.method = item.originalData.method
        delete item.originalData
        item.editing = false
    } else {
        // 没有原始数据，直接退出编辑模式
        item.editing = false
    }
}

const handleDeleteImmunity = async (id: number) => {
    try {
        await ElMessageBox.confirm('确定要删除这条免疫信息吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        console.log('正在删除免疫信息:', id)
        const response = await axios.delete(`${API_BASE_URL}/api/Farming/innunity/${getCurrentProductId()}`)
        if (response.status === 200) {
            ElMessage.success('删除成功')
            loadImmunityInfo() // 重新加载免疫信息
        }
    } catch (error: any) {
        if (error !== 'cancel') {
            // 静默处理错误
            console.log('删除失败，使用本地删除')
            // 如果API失败，使用本地删除
            const index = immunityList.value.findIndex(item => item.id === id)
            if (index !== -1) {
                immunityList.value.splice(index, 1)
                saveImmunityInfo() // 保存到localStorage
                ElMessage.success('删除成功（本地删除）')
            }
        }
    }
}

// 处理产品图片上传
const handleProductImageUpload = (file: any) => {
    const reader = new FileReader()
    reader.onload = (e) => {
        productInfo.coverImageUrl = e.target?.result as string
        saveProductInfo() // 保存到localStorage
        ElMessage.success('产品图片上传成功')
    }
    reader.readAsDataURL(file.raw)
}

// 删除产品图片
const handleDeleteProductImage = () => {
    productInfo.coverImageUrl = ''
    saveProductInfo() // 保存到localStorage
    ElMessage.success('产品图片已删除')
}

// 处理产品检验报告图片上传
const handleInspectionReportUpload = (file: any) => {
    const reader = new FileReader()
    reader.onload = (e) => {
        productInfo.inspectionReport = e.target?.result as string
        saveProductInfo() // 保存到localStorage
        ElMessage.success('产品检验报告上传成功')
    }
    reader.readAsDataURL(file.raw)
}

// 处理动检证图片上传
const handleCertificateUpload = (file: any) => {
    const reader = new FileReader()
    reader.onload = (e) => {
        farmingInfo.certificate = e.target?.result as string
        saveFarmingInfo() // 保存到localStorage
        ElMessage.success('动检证上传成功')
    }
    reader.readAsDataURL(file.raw)
}

// 处理企业照片上传
const handleEnterprisePhotoUpload = (file: any) => {
    const reader = new FileReader()
    reader.onload = (e) => {
        enterprisePhotos.value.push(e.target?.result as string)
        saveEnterprisePhotos() // 保存到localStorage
        ElMessage.success('企业照片上传成功')
    }
    reader.readAsDataURL(file.raw)
}

// 图片上传前的验证
const beforeImageUpload = (file: any) => {
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}

// 删除企业照片
const handleDeletePhoto = async (index: number) => {
    try {
        await ElMessageBox.confirm('确定要删除这张企业照片吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        // 尝试调用后端API删除
        try {
            const photoId = enterprisePhotos.value[index] // 假设有ID
            await axios.delete(`${API_BASE_URL}/api/Farming/enterprise/photo/${photoId}`)
            ElMessage.success('企业照片删除成功')
        } catch (apiError) {
            console.log('API删除失败，使用本地删除')
        }

        // 本地删除
        enterprisePhotos.value.splice(index, 1)
        saveEnterprisePhotos() // 保存到localStorage
        ElMessage.success('企业照片删除成功')
    } catch (error) {
        if (error !== 'cancel') {
            // 静默处理错误
            console.log('删除企业照片失败')
        }
    }
}

const handleSave = async () => {
    try {
        console.log('正在保存养殖信息:', farmingForm)
        const response = await axios.put(`${API_BASE_URL}/api/Farming`, farmingForm)
        if (response.status === 200) {
            ElMessage.success('保存成功')
            Object.assign(farmingInfo, farmingForm)
            saveFarmingInfo() // 保存到localStorage
            activePanel.value = 'farming-info'
        }
    } catch (error: any) {
        // 静默处理错误
        console.log('保存失败，使用本地保存')
        // 如果API失败，仍然保存到本地
        Object.assign(farmingInfo, farmingForm)
        saveFarmingInfo() // 保存到localStorage
        ElMessage.success('保存成功（本地保存）')
        activePanel.value = 'farming-info'
    }
}

// 保存企业信息
const handleSaveEnterprise = async () => {
    try {
        console.log('正在保存企业信息:', enterpriseForm)
        const response = await axios.put(`${API_BASE_URL}/api/Processing/enterprise`, enterpriseForm)

        if (response.status === 200) {
            ElMessage.success('企业信息保存成功')
            Object.assign(enterpriseInfo, enterpriseForm)
            saveEnterpriseInfo() // 保存到localStorage
            enterpriseDialogVisible.value = false
        }
    } catch (error: any) {
        // 静默处理错误
        console.log('保存企业信息失败，使用本地保存')
        Object.assign(enterpriseInfo, enterpriseForm)
        saveEnterpriseInfo() // 保存到localStorage
        ElMessage.success('企业信息保存成功（本地保存）')
        enterpriseDialogVisible.value = false
    }
}

const handleCancel = () => {
    ElMessage.info('已取消')
    activePanel.value = 'farming-info'
}

onMounted(() => {
    // 优先加载本地数据
    loadLocalData()

    // 然后尝试加载API数据
    loadProductDetail()
    loadFarmingInfo()
    loadImmunityInfo()
    loadProcessingInfo()
    loadSlaughterInfo()
})
</script>

<style scoped>
.traceability-detail-page {
    height: 100vh;
    width: 100vw;
    display: flex;
    flex-direction: column;
    background-color: #f5f5f5;
    margin: 0;
    padding: 0;
    overflow: hidden;
}

/* 顶部导航栏 */
.top-navigation {
    height: 60px;
    background-color: #2c3e50;
    color: white;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    flex-shrink: 0;
}

.nav-left .company-name {
    font-size: 16px;
    font-weight: bold;
}

.nav-center .module-tabs {
    background-color: transparent;
}

.nav-center :deep(.el-radio-button__inner) {
    background-color: transparent;
    border-color: #34495e;
    color: white;
}

.nav-center :deep(.el-radio-button__orig-radio:checked + .el-radio-button__inner) {
    background-color: #34495e;
    border-color: #34495e;
}

.nav-right {
    display: flex;
    align-items: center;
    gap: 15px;
}

.nav-icon {
    font-size: 18px;
    cursor: pointer;
}

.user-name,
.app-market,
.client {
    font-size: 14px;
    cursor: pointer;
}

/* 主容器 */
.main-container {
    flex: 1;
    display: flex;
    overflow: hidden;
}

/* 左侧菜单 */
.left-sidebar {
    width: 200px;
    background-color: #fff;
    border-right: 1px solid #e8e8e8;
    padding: 20px;
    flex-shrink: 0;
}

.sidebar-header {
    margin-bottom: 20px;
}

.page-title {
    font-size: 14px;
    color: #666;
    cursor: pointer;
}

.menu-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    cursor: pointer;
    border-radius: 4px;
    margin-bottom: 5px;
    transition: all 0.3s;
}

.menu-item:hover {
    background-color: #f0f0f0;
}

.menu-item.active {
    background-color: #e6f7ff;
    color: #1890ff;
}

/* 主内容区域 */
.content-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    overflow: hidden;
}

.content-header {
    padding: 20px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 10px;
}

.header-left h2 {
    margin: 0;
    color: #2c3e50;
}

.header-right {
    display: flex;
    gap: 10px;
}

/* 产品信息区域 */
.product-info-section {
    display: flex;
    padding: 20px;
    gap: 20px;
    border-bottom: 1px solid #e8e8e8;
}

.product-image img {
    width: 200px;
    height: 150px;
    object-fit: cover;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.product-image-upload {
    width: 200px;
    height: 150px;
    border: 2px dashed #d9d9d9;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
}

.product-image-upload:hover {
    border-color: #409eff;
    background-color: #f5f7fa;
}

.upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #999;
}

.upload-icon {
    font-size: 32px;
    margin-bottom: 8px;
}

.upload-text {
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 4px;
}

.upload-hint {
    font-size: 12px;
    color: #999;
}

.image-container {
    position: relative;
    width: 200px;
    height: 150px;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.image-container img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    opacity: 0;
    transition: opacity 0.3s;
}

.image-container:hover .image-overlay {
    opacity: 1;
}

.replace-upload {
    display: inline-block;
}

.product-details {
    flex: 1;
}

.product-name {
    font-size: 18px;
    font-weight: bold;
    color: #2c3e50;
    margin-bottom: 15px;
}

.detail-item {
    display: flex;
    margin-bottom: 10px;
}

.detail-item label {
    font-weight: bold;
    min-width: 120px;
    color: #2c3e50;
}

.inspection-report {
    margin-top: 20px;
}

.inspection-report label {
    display: block;
    font-weight: bold;
    margin-bottom: 10px;
    color: #2c3e50;
}

.report-upload {
    display: flex;
    align-items: center;
    gap: 10px;
}

.report-upload img {
    width: 60px;
    height: 40px;
    object-fit: cover;
    border-radius: 4px;
}

.add-icon {
    font-size: 24px;
    color: #999;
    cursor: pointer;
}

/* 信息标签页 */
.info-tabs-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.tab-nav {
    display: flex;
    background-color: #f8f9fa;
    border-bottom: 1px solid #e8e8e8;
}

.tab-nav-item {
    padding: 15px 20px;
    cursor: pointer;
    border-bottom: 2px solid transparent;
}

.tab-nav-item.active {
    border-bottom-color: #409eff;
    color: #409eff;
    background-color: #fff;
}

.tab-content {
    flex: 1;
    overflow: hidden;
}

.tab-panel {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.panel-tabs {
    display: flex;
    background-color: #f8f9fa;
    border-bottom: 1px solid #e8e8e8;
}

.panel-tab {
    padding: 12px 20px;
    cursor: pointer;
    border-bottom: 2px solid transparent;
}

.panel-tab.active {
    border-bottom-color: #409eff;
    color: #409eff;
    background-color: #fff;
}

.panel-content {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
}

/* 养殖信息显示 */
.farming-info-display {
    height: 100%;
}

.info-section {
    margin-bottom: 20px;
}

.info-item {
    display: flex;
    margin-bottom: 10px;
}

.info-item label {
    font-weight: bold;
    min-width: 100px;
    color: #2c3e50;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.section-header label {
    font-weight: bold;
    color: #2c3e50;
}

.immunity-table {
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 20px;
}

.table-header {
    display: flex;
    background-color: #f8f9fa;
    font-weight: bold;
}

.header-cell {
    flex: 1;
    padding: 10px;
    border-right: 1px solid #e8e8e8;
}

.table-row {
    display: flex;
    border-bottom: 1px solid #e8e8e8;
}

.table-row:last-child {
    border-bottom: none;
}

.table-cell {
    flex: 1;
    padding: 10px;
    border-right: 1px solid #e8e8e8;
    display: flex;
    align-items: center;
    justify-content: center;
}

.immunity-table .action-buttons {
    display: flex;
    gap: 4px;
    justify-content: center;
}

.immunity-table .action-buttons .el-button {
    padding: 4px 8px;
    font-size: 11px;
    min-width: 40px;
    height: 24px;
}

.immunity-table .table-cell .el-input {
    width: 100%;
}

.immunity-table .table-cell .el-input .el-input__inner {
    height: 24px;
    font-size: 12px;
}

.certificate-section {
    margin-bottom: 20px;
}

.certificate-section label {
    display: block;
    font-weight: bold;
    margin-bottom: 10px;
    color: #2c3e50;
}

.certificate-upload {
    display: flex;
    align-items: center;
    gap: 10px;
}

.certificate-upload img {
    width: 60px;
    height: 40px;
    object-fit: cover;
    border-radius: 4px;
}

.enterprise-section {
    margin-top: 20px;
}

.enterprise-info {
    margin-bottom: 20px;
}

.enterprise-photos {
    margin-top: 20px;
}

.enterprise-photos label {
    display: block;
    font-weight: bold;
    margin-bottom: 10px;
    color: #2c3e50;
}

.photos-upload {
    display: flex;
    align-items: center;
    gap: 10px;
    flex-wrap: wrap;
}

.photo-item {
    position: relative;
}

.photo-item img {
    width: 60px;
    height: 40px;
    object-fit: cover;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease;
}

.photo-item img:hover {
    transform: scale(1.1);
}

.delete-icon {
    position: absolute;
    top: -5px;
    right: -5px;
    font-size: 12px;
    color: #f56c6c;
    cursor: pointer;
    background-color: white;
    border-radius: 50%;
}

/* 养殖信息设置 */
.farming-settings {
    height: 100%;
}

.settings-form {
    max-width: 500px;
}

.form-buttons {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
}

.empty-content {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #999;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .product-info-section {
        flex-direction: column;
    }
}

@media (max-width: 768px) {
    .main-container {
        flex-direction: column;
    }

    .left-sidebar {
        width: 100%;
        height: auto;
    }

    .tab-nav {
        flex-wrap: wrap;
    }

    .tab-nav-item {
        flex: 1;
        min-width: 120px;
    }
}

/* 屠宰信息样式 */
.slaughter-content {
    padding: 20px;
}

.slaughter-section,
.qualification-section,
.enterprise-section {
    margin-bottom: 30px;
}

.slaughter-info,
.enterprise-info {
    padding: 15px;
    background: #f9f9f9;
    border-radius: 8px;
}

.qualification-info {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
}

.qualification-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    padding: 15px;
    background: #f9f9f9;
    border-radius: 8px;
    min-width: 200px;
}

.qualification-image img {
    width: 120px;
    height: 80px;
    object-fit: cover;
    border-radius: 4px;
    border: 1px solid #ddd;
}

.qualification-actions {
    display: flex;
    gap: 8px;
}

.qualification-actions .el-button {
    padding: 4px 12px;
    font-size: 12px;
}

.processing-section,
.food-safety-section,
.supplier-section {
    margin-bottom: 30px;
}

.supplier-item {
    margin-bottom: 20px;
    padding: 15px;
    background: #f9f9f9;
    border-radius: 8px;
}

.supplier-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.supplier-header label {
    font-weight: bold;
    color: #2c3e50;
}

.supplier-details {
    padding-left: 10px;
}

.material-images {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: center;
}

.material-image-item {
    position: relative;
}

.material-image-item img {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 4px;
    border: 1px solid #ddd;
    transition: transform 0.3s ease;
}

.material-image-item img:hover {
    transform: scale(1.05);
}

.material-image-item .delete-icon {
    position: absolute;
    top: -5px;
    right: -5px;
    font-size: 12px;
    color: #f56c6c;
    cursor: pointer;
    background-color: white;
    border-radius: 50%;
    padding: 2px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
}

.material-image-item .delete-icon:hover {
    background-color: #f56c6c;
    color: white;
    transform: scale(1.1);
}

.image-upload img {
    width: 100px;
    height: 100px;
    object-fit: cover;
    border-radius: 8px;
}

.address-selector {
    display: flex;
    gap: 10px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>